from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import render, redirect

from CNAS1 import settings
from app import models


class DemoMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.path_info == '/login/' or request.path_info == '/register/':
            return None

        # 读取当前访问的用户的session信息，如果能读到说明已经登录
        info_dict = request.session.get('user_info')
        if not info_dict:
            return redirect('/login/')

        # 设置用户信息到request对象
        request.unicom_userid = info_dict['user_id']
        request.unicom_username = info_dict['username']
        request.unicom_full_name = info_dict['full_name']

        # 检查URL权限
        url_name = request.resolver_match.url_name if hasattr(request.resolver_match, 'url_name') else None
        if url_name and url_name in settings.UNICOM_PERMISSION.get(info_dict['role'], []):
            return None

        # 对于特定证书路径，检查型号权限
        if request.path_info.startswith(('/kfv/', '/kfc/', '/dwy/', '/ph/','/hma/','/lz/','/ddl/')):
            cert_type = request.path_info.split('/')[1].upper()
            user_info = models.UserInfo.objects.filter(username=info_dict['username']).first()
            # 直接检查布尔型权限字段
            if not user_info or not getattr(user_info, f'{cert_type.lower()}_cert_permission', False):
                return HttpResponse('无权限访问此证书', status=403)

        return None

    # 删除process_view方法，因为权限检查已移到process_request中
